{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XNWJ6JVGkOlf"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors. [Licensed under the Apache License, Version 2.0](#scrollTo=bPJq2qP2KE3u)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "fSlQ2vFzKGOY"
      },
      "outputs": [],
      "source": [
        "// #@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\n",
        "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "// you may not use this file except in compliance with the License.\n",
        "// You may obtain a copy of the License at\n",
        "//\n",
        "// https://www.apache.org/licenses/LICENSE-2.0\n",
        "//\n",
        "// Unless required by applicable law or agreed to in writing, software\n",
        "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "// See the License for the specific language governing permissions and\n",
        "// limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yfNdITLmJtX8"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/swift/tutorials/raw_tensorflow_operators\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/swift/blob/main/docs/site/tutorials/raw_tensorflow_operators.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/swift/blob/main/docs/site/tutorials/raw_tensorflow_operators.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lONNcRalVUO9"
      },
      "source": [
        "# Raw TensorFlow operators\n",
        "\n",
        "Building on TensorFlow, Swift for TensorFlow takes a fresh approach to API design. APIs are carefully curated from established libraries and combined with new language idioms. This means that not all TensorFlow APIs will be directly available as Swift APIs, and our API curation needs time and dedicated effort to evolve. However, do not worry if your favorite TensorFlow operator is not available in Swift -- the TensorFlow Swift library gives you transparent access to most TensorFlow operators, under the `_Raw` namespace.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CYqNvcHxqg0Y"
      },
      "source": [
        "Import `TensorFlow` to get started."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cVRrzjzFqee9"
      },
      "outputs": [],
      "source": [
        "import TensorFlow"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5vza91sR09r-"
      },
      "source": [
        "## Calling raw operators\n",
        "\n",
        "Simply find the function you need under the `_Raw` namespace via code completion."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kZRlD4utdPuX"
      },
      "outputs": [],
      "source": [
        "print(_Raw.mul(Tensor([2.0, 3.0]), Tensor([5.0, 6.0])))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iIgKg-ueVCy_"
      },
      "source": [
        "## Defining a new multiply operator\n",
        "\n",
        "Multiply is already available as operator `*` on `Tensor`, but let us pretend that we wanted to make it available under a new name as `.*`. Swift allows you to retroactively add methods or computed properties to existing types using `extension` declarations.\n",
        "\n",
        "Now, let us add `.*` to `Tensor` by declaring an extension and make it available when the tensor's `Scalar` type conforms to [`Numeric`](https://developer.apple.com/documentation/swift/numeric)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BdH-yZBjTZNx"
      },
      "outputs": [],
      "source": [
        "infix operator .* : MultiplicationPrecedence\n",
        "\n",
        "extension Tensor where Scalar: Numeric {\n",
        "    static func .* (_ lhs: Tensor, _ rhs: Tensor) -> Tensor {\n",
        "        return _Raw.mul(lhs, rhs)\n",
        "    }\n",
        "}\n",
        "\n",
        "let x: Tensor<Double> = [[1.0, 2.0], [3.0, 4.0]]\n",
        "let y: Tensor<Double> = [[8.0, 7.0], [6.0, 5.0]]\n",
        "print(x .* y)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ucD5XZYYyzNe"
      },
      "source": [
        "## Defining a derivative of a wrapped function\n",
        "\n",
        "Not only can you easily define a Swift API for a raw TensorFlow operator, you can also make it differentiable to work with Swift's first-class automatic differentiation.\n",
        "\n",
        "To make `.*` differentiable, use the `@derivative` attribute on the derivative function and specify the original function as an attribute argument under the `of:` label. Since the `.*` operator is defined when the generic type `Scalar` conforms to `Numeric`, it is not enough for making `Tensor<Scalar>` conform to the `Differentiable` protocol. Born with type safety, Swift will remind us to add a generic constraint on the `@differentiable` attribute to require `Scalar` to conform to `TensorFlowFloatingPoint` protocol, which would make `Tensor<Scalar>` conform to `Differentiable`.\n",
        "\n",
        "```swift\n",
        "@differentiable(where Scalar: TensorFlowFloatingPoint)\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fDXS0h_YumcL"
      },
      "outputs": [],
      "source": [
        "infix operator .* : MultiplicationPrecedence\n",
        "\n",
        "extension Tensor where Scalar: Numeric {\n",
        "    @differentiable(where Scalar: TensorFlowFloatingPoint)\n",
        "    static func .* (_ lhs: Tensor,  _ rhs: Tensor) -> Tensor {\n",
        "        return _Raw.mul(lhs, rhs)\n",
        "    }\n",
        "}\n",
        "\n",
        "extension Tensor where Scalar : TensorFlowFloatingPoint { \n",
        "    @derivative(of: .*)\n",
        "    static func multiplyDerivative(\n",
        "        _ lhs: Tensor, _ rhs: Tensor\n",
        "    ) -> (value: Tensor, pullback: (Tensor) -> (Tensor, Tensor)) {\n",
        "        return (lhs * rhs, { v in\n",
        "            ((rhs * v).unbroadcasted(to: lhs.shape),\n",
        "            (lhs * v).unbroadcasted(to: rhs.shape))\n",
        "        })\n",
        "    }\n",
        "}\n",
        "\n",
        "// Now, we can take the derivative of a function that calls `.*` that we just defined.\n",
        "print(gradient(at: x, y) { x, y in\n",
        "    (x .* y).sum()\n",
        "})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l7kae5o1VKnu"
      },
      "source": [
        "## More examples"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "v92FrXpCSuLT"
      },
      "outputs": [],
      "source": [
        "let matrix = Tensor<Float>([[1, 2], [3, 4]])\n",
        "\n",
        "print(_Raw.matMul(matrix, matrix, transposeA: true, transposeB: true))\n",
        "print(_Raw.matMul(matrix, matrix, transposeA: true, transposeB: false))\n",
        "print(_Raw.matMul(matrix, matrix, transposeA: false, transposeB: true))\n",
        "print(_Raw.matMul(matrix, matrix, transposeA: false, transposeB: false))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "raw_tensorflow_operators.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Swift",
      "name": "swift"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
